
package com.william.killian.trivia.model;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

@Root (name = "HighScores")
public class HighScoreList
{
    
    @ElementList (inline = true)
    private ArrayList <HighScoreEntry> list;

    public HighScoreList () {
        list = new ArrayList <HighScoreEntry> ();
    }

    public void add (Integer score, String name)
    {
        list.add (new HighScoreEntry (name, score));
    }

    public void save (File f)
    {
        try
        {
            Collections.sort (list);
            f.getParentFile ().mkdir ();
            Serializer serializer = new Persister ();
            serializer.write (this, f);
        }
        catch (Exception e)
        {
            e.printStackTrace ();
        }
    }

    public ArrayList <HighScoreEntry> getScores ()
    {
        Collections.sort (list);
        return list;
    }

    public static HighScoreList Load (File f)
    {
        try
        {
            Serializer serializer = new Persister ();
            HighScoreList list = serializer.read (HighScoreList.class, f);
            return list;
        }
        catch (Exception e)
        {
            return new HighScoreList ();
        }
    }
}
